package com.presto.directo.mvvm.view

import android.Manifest
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.provider.Settings
import android.view.View
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.widget.doOnTextChanged
import com.presto.directo.R
import com.presto.directo.base.BaseActivity
import com.presto.directo.databinding.ActivityContactinfoBinding
import com.presto.directo.mvvm.viewmodel.ContactViewModel
import com.presto.directo.mvvm.viewmodel.getViewModel
import com.presto.directo.net.getHttpMap
import com.presto.directo.utils.*
import com.tbruyelle.rxpermissions3.RxPermissions
import ru.whalemare.sheetmenu.SheetMenu

class InfoContactActivity : BaseActivity() {
    override val rootView: View
        get() = binding.root
    private val views by lazy {
        listOf(
            binding.tvRelationship1,
            binding.tvPhone1,
            binding.etName1,
            binding.tvRelationship2,
            binding.tvPhone2,
            binding.etName2
        )
    }
    private val binding by lazy { ActivityContactinfoBinding.inflate(layoutInflater) }
    private val viewModel: ContactViewModel by lazy { getViewModel() }

    private val launch1 = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode != RESULT_OK) return@registerForActivityResult
        getContact(1, it.data?.data)
    }
    private val launch2 = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode != RESULT_OK) return@registerForActivityResult
        getContact(2, it.data?.data)
    }

    private var isFocusable = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Af.show_contact_page.track(this)
        viewModel.infoLiveData.observe(this) {
            showInfo(binding.tvRelationship1, R.array.array_relation_ships, viewModel.relationship1)
            showInfo(binding.tvRelationship2, R.array.array_relation_ships, viewModel.relationship2)
            binding.tvPhone1.setText(it.phone_relation_1)
            binding.etName1.setText(it.name_relation_1)
            binding.tvPhone2.setText(it.phone_relation_2)
            binding.etName2.setText(it.name_relation_2)
        }
        viewModel.uploadLiveData.observe(this) {
            Af.success_submit_contactInfo.track(this)
            startActivity(Intent(this, InfoPersonActivity::class.java))
            finish()
        }
        viewModel.getInfo()
    }

    override fun initEvent() {
        views.forEach { it.doOnTextChanged { text, start, before, count -> updateBtn() } }
        setClick(binding.tvRelationship1, R.array.array_relation_ships)
        setClick(binding.tvRelationship2, R.array.array_relation_ships)
        binding.ivPhone1.setOnClickListener { pickContact(launch1) }
        binding.tvPhone1.setOnClickListener {
            if (!isFocusable) {
                binding.ivPhone1.performClick()
            }
        }
        binding.etName1.setOnClickListener { binding.tvPhone1.performClick() }
        binding.ivPhone2.setOnClickListener { pickContact(launch2) }
        binding.tvPhone2.setOnClickListener {
            if (!isFocusable) {
                binding.ivPhone2.performClick()
            }
        }
        binding.etName2.setOnClickListener { binding.tvPhone2.performClick() }
        binding.btnNext.setOnClickListener {
            Af.click_submit_contactInfo.track(this)
            val map = getHttpMap()
            map["relation_1"] = viewModel.relationship1
            map["relation_2"] = viewModel.relationship2
            map["name_relation_1"] = binding.etName1.text.toString()
            map["name_relation_2"] = binding.etName2.text.toString()
            map["phone_relation_1"] = binding.tvPhone1.text.toString()
            map["phone_relation_2"] = binding.tvPhone2.text.toString()
            viewModel.upload(map)
        }
    }

    private fun setClick(textView: TextView, res: Int) {
        textView.setOnClickListener {
            SheetMenu(
                actions = resources.getStringArray(res).asList(),
                onClick = {
                    textView.text = it.title
                    when (textView) {
                        binding.tvRelationship1 -> viewModel.relationship1 = it.id + 1
                        binding.tvRelationship2 -> viewModel.relationship2 = it.id + 1
                    }
                },
                layoutProvider = MyLayoutProvider()
            ).show(this)
        }
    }

    private fun pickContact(launch: ActivityResultLauncher<Intent>) {
        RxPermissions(this)
            .request(Manifest.permission.READ_CONTACTS)
            .getResponse(this, {
                if (it) {
                    launch.launch(
                        Intent(
                            Intent.ACTION_PICK,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                        )
                    )
                } else {
                    Intent().apply {
                        action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                        data = Uri.parse("package:$packageName")
                        startActivity(this)
                    }
                }
            })
    }

    private fun getContact(requestCode: Int, uri: Uri?) {
        var cursor: Cursor? = null
        try {
            cursor = contentResolver.query(uri!!, null, null, null, null)
            cursor!!.moveToFirst()
            val contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
            val mobileNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
            if (requestCode == 1) {
                binding.tvPhone1.setText(mobileNum)
                binding.etName1.setText(contactName)
            } else {
                binding.tvPhone2.setText(mobileNum)
                binding.etName2.setText(contactName)
            }
            cursor.close()
        } catch (e: Exception) {
            isFocusable = true
            binding.tvPhone1.isFocusableInTouchMode = true
            binding.etName1.isFocusableInTouchMode = true
            binding.tvPhone2.isFocusableInTouchMode = true
            binding.etName2.isFocusableInTouchMode = true
        } finally {
            cursor?.close()
        }

    }

    override fun updateBtn() {
        binding.btnNext.isEnabled = views.all { it.text.isNotBlank() }
    }

}